package com.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/*
 * 数据库支持类,使用单例模式
 */
public class DBmanager {
	private static String user = "root";
	private static String pwd = "adminma";	
	private static String URL = "jdbc:mysql://localhost:3306/WeChat?useSSL=false&serverTimezone=UTC";	
	private static String driver = "com.mysql.cj.jdbc.Driver";		
	private static DBmanager db = null;		//单例模式,唯一对象
	
	//静态加载数据库驱动类
	static {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			System.out.println("静态加载数据库驱动类失败！");
			e.printStackTrace();			
		}
	}
	
	//私有构造函数
	private DBmanager() {
	
	}
	
	//获取数据库,双重锁定,保证线程安全
	public static DBmanager getInstance() {
		if(db == null) {
			synchronized(DBmanager.class) {
				if(db == null)
					db = new DBmanager();
			}
		}
		if(db == null) {
			System.out.println("getInstance: db为null！");
		}
		return db;		
	}
	
	//获取数据库连接
	public Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(URL, user, pwd);
			if(conn == null)
				System.out.println("getConnection: conn为null！");
			return conn;
		} catch (SQLException e) {
			System.out.println("获取conn失败！");
			e.printStackTrace();
			return null;
		}
	}

}
